package com.example.controller;

import com.example.common.AutoLog;
import com.example.common.CaptureConfig;
import com.example.common.Result;
import com.example.entity.Admin;
import com.example.entity.Params;
import com.example.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wf.captcha.utils.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    AdminService adminService;

    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }

    @PostMapping("/login")
    @AutoLog("登录系统")
    public Result login(@RequestBody Admin admin, @RequestParam String key, HttpServletRequest request){
        if (!admin.getVerCode().equals(CaptureConfig.CAPTURE_MAP.get(key))){
//            CaptchaUtil.clear(request); //这是前后端分离session中使用的，这里可以不管。
            return Result.error("验证码不正确");
        }
        Admin user = adminService.login(admin);
        CaptureConfig.CAPTURE_MAP.remove(key);
        return Result.success(user);
    }

    @GetMapping("/search")
    public Result findBySearch(Params params){
        log.info("进入了/admin/search接口");
        //1.开启分页
        PageHelper.startPage(params.getPageNum(),params.getPageSize());
        //2.查询信息
        List<Admin> list = adminService.findBySearch(params); //不展示管理员的那条信息，用sql写
        //3.封装对象
        PageInfo<Admin> info = PageInfo.of(list);
        return Result.success(info);
    }

    @PostMapping
    public Result save(@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result del(@PathVariable Integer id){
        adminService.removeById(id);
        return Result.success();
    }
}

